package com.yuyou.fn.platform.service.impl;

import com.github.wens.framework.service.impl.SuperServiceImpl;
import com.github.wens.mybatisplus.examples.Example;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.platform.constant.AdminResourceEnum;
import com.yuyou.fn.platform.entity.SysRole;
import com.yuyou.fn.platform.mapper.SysRoleMapper;
import com.yuyou.fn.platform.service.ISysRoleResourceService;
import com.yuyou.fn.platform.service.ISysRoleService;
import com.yuyou.fn.platform.service.ISysUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 *
 * SysRole 表数据服务层接口实现类
 *
 */
@Service
public class SysRoleServiceImpl extends SuperServiceImpl<SysRoleMapper, SysRole,Long> implements ISysRoleService {

    @Resource
    private ISysRoleResourceService sysRoleResourceService ;

    @Resource
    private ISysUserRoleService sysUserRoleService ;

    @Override
    public void saveOrUpdateRole(Long roleId , String roleName){
        Example<SysRole> example=SysRole.createExample();
        example.createCriteria().andEqualTo("roleName",roleName);
        SysRole check=this.findOneByExample(example);
        if (check!=null){
            throw new BusException("该角色名已存在");
        }

        if(roleId == null ){
            SysRole sysRole = new SysRole();
            sysRole.setRoleName(roleName);
            sysRole.setCreateTime(TimeUtils.now());
            sysRole.setUpdateTime(TimeUtils.now());
            insertSelective(sysRole);
        }else{
            SysRole sysRole = new SysRole();
            sysRole.setRoleName(roleName);
            sysRole.setRoleId(roleId);
            sysRole.setUpdateTime(TimeUtils.now());
            updateSelectiveById(sysRole);
        }
    }

    @Transactional
    @Override
    public void deleteRole(Long roleId) {
        if (checkIfAdmin(roleId)){
            throw new BusException("系统管理员的角色不可删除");
        }
        sysUserRoleService.deleteUserRole( null , roleId );
        sysRoleResourceService.deleteRoleResource(roleId);
        deleteById(roleId);
    }

    private Boolean checkIfAdmin(Long roleId){
        if (roleId.equals(AdminResourceEnum.adminRole.id)){
            return true;
        }
        return false;
    }

    @Override
    public List<SysRole> findAll() {
        return findListByExample(SysRole.createExample());
    }

    @Override
    public List<SysRole> findSysRoleByRoleNames(List<String> roleNames) {
        if (Utils.checkListEmpty(roleNames)){
            return Collections.EMPTY_LIST;
        }
        Example<SysRole> example=SysRole.createExample();
        example.createCriteria().andIn("roleName",roleNames);
        return findListByExample(example);
    }
}